import React, { Component } from 'react'
import PostItem from './PostItem.js'
import PlusButton from './PlusButton.jsx';
import axios from 'axios';

class PostList extends Component {

    constructor(props) {
        super(props);
        this.state = {
            dataArray: []
        };
        this.arrData = [];
        this.timer = null;
        this.changeData = this.changeData.bind(this);
        this.initData = this.initData.bind(this);
    }

    componentDidMount() {
        this.initData();
    }

    async initData() {
        let res = await axios.get("http://localhost:3005/list");
        this.arrData = await res.data;
        this.timer = setTimeout(() => {
            this.setState({
                dataArray: [
                    ...this.arrData
                ]
            });
        }, 1000);
    }

    componentWillUnmount() {
        if (this.timer) {
            clearTimeout(this.timer);
        }
    }

    changeData() {
        this.arrData[1].title = "不是";
        this.setState({
            dataArray: [
                ...this.arrData
            ]
        })
    }

    render() {
        return (
            <>
                <h3>帖子列表</h3>
                <ul>
                    {this.state.dataArray.map(item => 
                        <PostItem
                            key={item.id}
                            title={item.title}
                            author={item.author}
                            date={item.date}
                        />
                    )}
                </ul>
                <PlusButton />
                <button onClick={this.changeData}>plus me</button>
            </>
        );
    }
    
}

export default PostList;